import os
import unittest
# import os
from unittestreport import TestRunner

from config.config import ROOT_DIR, REPORT_DIR

# 测试用例目录
test_dir = os.path.join(ROOT_DIR, "..", "testcases")
print("测试用例目录", test_dir)
# 创建测试套件
suite = unittest.defaultTestLoader.discover(test_dir, pattern="test_*.py")

# 运行测试并生成报告
runner = TestRunner(
    suite=suite,
    filename="test_report.html",
    report_dir=REPORT_DIR,
    title="UI自动化测试报告",
    tester="自动化测试系统",
    desc="使用unittest+selenium+POM模式的UI自动化测试",
    templates=1
)

# 执行测试
runner.run()

# 获取最新的测试报告文件
report_files = [f for f in os.listdir(REPORT_DIR) if f.endswith(".html")]
if report_files:
    latest_report = os.path.join(REPORT_DIR,
                                 max(report_files, key=lambda x: os.path.getctime(os.path.join(REPORT_DIR, x))))

    # 获取所有截图
    screenshot_dir = os.path.join(ROOT_DIR, "..", "screenshots")
    screenshots = []
    if os.path.exists(screenshot_dir):
        screenshots = [os.path.join(screenshot_dir, f) for f in os.listdir(screenshot_dir) if f.endswith(".png")]

    # 发送邮件
    # email_tool = EmailTool(EMAIL_CONFIG)
    # email_tool.send_email(latest_report, screenshots)
else:
    print("未找到测试报告文件")